import React, { Component } from 'react';
import { Button, Modal, Select, Form, Row, Col, Input, DatePicker, Radio, message } from 'antd';
import { connect } from 'dva';
const { TextArea } = Input;
import style from './index.css';
import BaseComponent from '@/components/BaseComponent';
import moment from 'moment';
import ReportCard from '@/components/ReportCard';

@connect(({ user }) => ({
  // data: risk.riskData,
  currentUser: user.currentUser,
}))
@Form.create()
export default class index extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      form: {},
      allTableData: [],
      provinceIdData: [],
      cityIdData: [],
      districtIdData: [],
      countyIdData: [],
      villageIdData: [],
      nationCodeData: [],
    };
  }

  showModal = () => {
    this.getCity({ level: 1, parentCode: '' });
    this.nationlist();
    this.findById();
    this.setState({
      visible: true,
    });
  };

  handleOk = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState(
          params => ({
            form: {
              ...params.form,
              id: this.props.record.id,
            },
          }),
          () => {
            this.updateRecord(this.state.form);
          },
        );
        this.setState({
          visible: false,
        });
      }
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };

  handleUploadBefore = (file, fileList) => {
    this.setState({ isUploading: true }, () => {
      this.hide = this.loadingMessage('正在上传...');
    });
    return true;
  };
  handleBlUploadChange = ({ info }) => {
    if (info.file.status !== 'uploading') {
      this.setState(
        {
          fileList: info.fileList,
        },
        () => { }
      );
    }
    if (info.file.status === 'done') {
      const response = info.file.response;
      const {
        data: { filePath, originalFilename },
      } = response;
      const arr = filePath.split('/');
      // 文件前缀
      const prefix = arr[arr.length - 2];
      const url = `${prefix}/${originalFilename}`;

      this.setState(params => ({
        form: {
          ...params.form,
          writtenConsentFilePath: filePath,
          writtenConsentUrl: url,
        },
        isUploading: false,
      }));
      if (this.hide) {
        this.hide();
      }
      this.successMessage('上传成功');
    } else if (info.file.status === 'error') {
      this.errorMessage('文件上传出错,请联系管理员');
    }
  };
  handleDelBlImage = () => {
    this.setState(params => ({
      form: {
        ...params.form,
        writtenConsentFilePath: '',
        writtenConsentUrl: '',
      },
    }));
  };

  provinceIdChange = value => {
    const str = value ? this.state.provinceIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          provinceId: value,
          provinceName: name,
        },
      }),
      () => {
        this.getCity({ level: 2, parentCode: value });
      }
    );
  };
  cityIdChange = value => {
    const str = value ? this.state.cityIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          cityId: value,
          cityName: name,
        },
      }),
      () => {
        this.getCity({ level: 3, parentCode: value });
      }
    );
  };
  districtIdChange = value => {
    const str = value ? this.state.districtIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          districtId: value,
          districtName: name,
        },
      }),
      () => {
        this.getCity({ level: 4, parentCode: value });
      }
    );
  };
  countyIdChange = value => {
    const str = value ? this.state.countyIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          countyId: value,
          countyName: name,
        },
      }),
      () => {
        this.getCity({ level: 5, parentCode: value });
      }
    );
  };

  villageIdChange = value => {
    const str = value ? this.state.villageIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(params => ({
      form: {
        ...params.form,
        villageId: value,
        villageName: name,
      },
    }));
  };

  nameChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        name: value,
      },
    }));
  };

  sexChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        sex: value,
      },
    }));
  };

  nationCodeChange = value => {
    if (value !== -1) {
      const person = this.state.nationCodeData[value - 1];
      this.setState(params => ({
        form: {
          ...params.form,
          nationCode: value,
          nationName: person,
        },
      }));
    }
  };
  birthdayChange = (date, dateString) => {
    console.log(date, dateString);
    this.setState(params => ({
      form: {
        ...params.form,
        birthday: dateString,
      },
    }));
  };

  addrChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        addr: value,
      },
    }));
  };

  sfzChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        sfz: value,
      },
    }));
  };

  qfjgChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        qfjg: value,
      },
    }));
  };

  yxStartDateChange = (date, dateString) => {
    console.log(date, dateString);
    this.setState(params => ({
      form: {
        ...params.form,
        yxStartDate: dateString,
      },
    }));
  };

  yxEndDateChange = (date, dateString) => {
    console.log(date, dateString);
    this.setState(params => ({
      form: {
        ...params.form,
        yxEndDate: dateString,
      },
    }));
  };
  phoneChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        phone: value,
      },
    }));
  };
  selfSignDateChange = (date, dateString) => {
    console.log(date, dateString);
    this.setState(params => ({
      form: {
        ...params.form,
        selfSignDate: dateString,
      },
    }));
  };
  proofDateChange = (date, dateString) => {
    console.log(date, dateString);
    this.setState(params => ({
      form: {
        ...params.form,
        proofDate: dateString,
      },
    }));
  };
  proofNameChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        proofName: value,
      },
    }));
  };

  screeningTypeChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        screeningType: value,
      },
    }));
  };

  //查询省
  getCity = param => {
    this.execHttp('plannedFollowUp/getCity', { ...param }).then(resp => {
      if (resp) {
        if (param.level == 1) {
          this.setState({
            provinceIdData: resp.data,
          });
        } else if (param.level == 2) {
          this.setState({
            cityIdData: resp.data,
          });
        } else if (param.level == 3) {
          this.setState({
            districtIdData: resp.data,
          });
        } else if (param.level == 4) {
          this.setState({
            countyIdData: resp.data,
          });
        } else if (param.level == 5) {
          this.setState({
            villageIdData: resp.data,
          });
        }
      }
    });
  };
  //民族  nationlist
  nationlist = () => {
    this.execHttp('personalInformation/nationlist').then(resp => {
      if (resp) {
        this.setState({
          nationCodeData: resp.data,
        });
      }
    });
  };

  //同意书
  updateRecord = from => {
    this.execHttp('crowdDataReport/updateRecord', {
      ...from,
    }).then(resp => {
      if (resp && resp.success) {
        message.success(resp.message);
        this.props.getDataByPage();
      } else {
        message.error(resp.message);
      }
    });
  };

  /**详情*/
  findById = () => {
    this.execHttp('crowdDataReport/findById', {
      id: this.props.record.id,
    }).then(resp => {
      if (resp && resp.success) {
        this.setState({
          form: resp.data.response,
        });
        this.getCity({ level: 2, parentCode: '34' });
        this.getCity({ level: 3, parentCode: resp.data.response.cityId });
        this.getCity({ level: 4, parentCode: resp.data.response.districtId });
        this.getCity({ level: 5, parentCode: resp.data.response.countyId });
      }
    });
  };

  render() {
    const { visible, confirmLoading } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };

    const { record } = this.props;
    const color = record.written_consent_url ? '#67c23a' : '#e6a23c';
    //written_consent_url
    return (
      <div style={{ display: 'inline-block' }}>
        {/* #67c23a #e6a23c */}
        <Button
          type="primary"
          style={{ marginLeft: '10px', background: color, borderColor: color }}
          onClick={this.showModal}
        >
          同意书
        </Button>
        <Modal
          title="同意书查看"
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          onCancel={this.handleCancel}
          width={1500}
        >
          <div>
            <Row gutter={16}>
              <Form {...formItemLayout}>
                <Row gutter={16}>
                  <Col span={8}>
                    <Form.Item label="所属省份">
                      <Select
                        allowClear
                        value={this.state.form.provinceId}
                        onChange={this.provinceIdChange}
                        style={{ width: 200 }}
                        placeholder="请选择所属省份"
                        disabled
                      >
                        {this.state.provinceIdData.map(item => (
                          <Select.Option key={item.code}>{item.name}</Select.Option>
                        ))}
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="所属城市">
                      <Select
                        allowClear
                        value={this.state.form.cityId}
                        onChange={this.cityIdChange}
                        style={{ width: 200 }}
                        placeholder="请选择所属省份"
                        disabled
                      >
                        {this.state.cityIdData.map(item => (
                          <Select.Option key={item.code}>{item.name}</Select.Option>
                        ))}
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="所属区/县">
                      <Select
                        allowClear
                        value={this.state.form.districtId}
                        onChange={this.districtIdChange}
                        style={{ width: 200 }}
                        placeholder="请选择所属省份"
                        disabled
                      >
                        {this.state.districtIdData.map(item => (
                          <Select.Option key={item.code}>{item.name}</Select.Option>
                        ))}
                      </Select>
                    </Form.Item>
                  </Col>

                </Row>

                <Row gutter={16}>
                  <Col span={8}>
                    <Form.Item label="所属乡镇">
                      <Select
                        allowClear
                        value={this.state.form.countyId}
                        onChange={this.countyIdChange}
                        style={{ width: 200 }}
                        placeholder="请选择所属乡镇"
                        disabled
                      >
                        {this.state.countyIdData.map(item => (
                          <Select.Option key={item.code}>{item.name}</Select.Option>
                        ))}
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="所属村">
                      <Select
                        allowClear
                        value={this.state.form.villageId}
                        onChange={this.villageIdChange}
                        style={{ width: 200 }}
                        placeholder="请选择所属村"
                        disabled
                      >
                        {this.state.villageIdData.map(item => (
                          <Select.Option key={item.code}>{item.name}</Select.Option>
                        ))}
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="姓名">
                      <Input
                        placeholder="姓名"
                        value={this.state.form.name}
                        onChange={this.nameChange}
                        style={{ width: 200 }}
                        disabled
                      />
                    </Form.Item>
                  </Col>

                </Row>

                <Row gutter={16}>

                  <Col span={8}>
                    <Form.Item label="性别">
                      <Radio.Group value={this.state.form.sex} onChange={this.sexChange} disabled>
                        <Radio value={'男'}>男</Radio>
                        <Radio value={'女'}>女</Radio>
                      </Radio.Group>
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="民族">
                      <Select
                        allowClear
                        value={this.state.form.nationCode}
                        onChange={this.nationCodeChange}
                        style={{ width: 200 }}
                        placeholder="请选择所属村"
                        disabled
                      >
                        {this.state.nationCodeData.map((item, index) => (
                          <Select.Option key={index + 1}>{item}</Select.Option>
                        ))}
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="出生日期">
                      <DatePicker
                        style={{ width: 200 }}
                        showTime
                        format="YYYY-MM-DD"
                        value={
                          this.state.form.birthday === null || undefined
                            ? this.state.form.birthday
                            : moment(this.state.form.birthday, 'YYYY-MM-DD')
                        }
                        onChange={this.birthdayChange}
                        disabled
                      />
                    </Form.Item>
                  </Col>

                </Row>

                <Row gutter={16}>
                  <Col span={8}>
                    <Form.Item label="住址">
                      <Input
                        placeholder="住址"
                        value={this.state.form.addr}
                        onChange={this.addrChange}
                        style={{ width: 200 }}
                        disabled
                      />
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="身份证号码">
                      <Input
                        placeholder="身份证号码"
                        value={this.state.form.sfz}
                        onChange={this.sfzChange}
                        style={{ width: 200 }}
                        disabled
                      />
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="签发机关">
                      <Input
                        placeholder="签发机关"
                        value={this.state.form.qfjg}
                        onChange={this.qfjgChange}
                        style={{ width: 200 }}
                        disabled
                      />
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={16}>
                  <Col span={8}>
                    <Form.Item label="有限期限起始">
                      <DatePicker
                        style={{ width: 200 }}
                        showTime
                        format="YYYY-MM-DD"
                        value={
                          this.state.form.yxStartDate === null || undefined
                            ? this.state.form.yxStartDate
                            : moment(this.state.form.yxStartDate, 'YYYY-MM-DD')
                        }
                        onChange={this.yxStartDateChange}
                        disabled
                      />
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="有限期限结束">
                      <DatePicker
                        style={{ width: 200 }}
                        showTime
                        format="YYYY-MM-DD"
                        value={
                          this.state.form.yxEndDate === null || undefined
                            ? this.state.form.yxEndDate
                            : moment(this.state.form.yxEndDate, 'YYYY-MM-DD')
                        }
                        onChange={this.yxEndDateChange}
                        disabled
                      />
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="手机号">
                      <Input
                        placeholder="手机号"
                        value={this.state.form.phone}
                        onChange={this.phoneChange}
                        style={{ width: 200 }}
                        disabled
                      />
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={16}>
                  <Col span={24}>
                    <Form.Item labelCol={{ span: 2, offset: 0 }} label="同意书">
                      <ReportCard
                        imagePreview={true}
                        emptyMsg={'暂无同意书,请上传同意书'}
                        uploadBtnLabel={'上传同意书'}
                        fileUrl={this.state.form.writtenConsentUrl}
                        isUploading={this.state.isUploading}
                        beforeUpload={this.handleUploadBefore}
                        onChange={this.handleBlUploadChange}
                        onDelClick={this.handleDelBlImage}
                      ></ReportCard>
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={16}>
                  <Col span={8}>
                    <Form.Item label="自我申请签订日期">
                      {getFieldDecorator('selfSignDate', {
                        initialValue: this.state.form.selfSignDate === null ? null : moment(this.state.form.selfSignDate, 'YYYY-MM-DD'),
                        rules: [{ required: true, message: '签订日期不能为空' }],
                      })(
                        <DatePicker
                          style={{ width: 200 }}
                          showTime
                          format="YYYY-MM-DD"
                          onChange={this.selfSignDateChange}
                        />
                      )}
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="证明人声明日期">
                      {getFieldDecorator('proofDate', {
                        initialValue: this.state.form.proofDate === null ? null : moment(this.state.form.proofDate, 'YYYY-MM-DD'),
                        rules: [{ required: true, message: '声明日期不能为空' }],
                      })(
                        <DatePicker
                          style={{ width: 200 }}
                          showTime
                          format="YYYY-MM-DD"
                          onChange={this.proofDateChange}
                        />
                      )}
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="证明人姓名">
                      {getFieldDecorator('proofName', {
                        initialValue: this.state.form.proofName,
                        rules: [{ required: true, message: '姓名不能为空' }],
                      })(
                        <Input
                          placeholder="证明人姓名"
                          onChange={this.proofNameChange}
                          style={{ width: 200 }}
                        />
                      )}
                    </Form.Item>
                  </Col>
                </Row>

                <Row>
                  <Col span={8}>
                    <Form.Item label="筛查类型">
                      <Radio.Group
                        value={this.state.form.screeningType}
                        onChange={this.screeningTypeChange}
                      >
                        <Radio value={0}>初筛</Radio>
                        <Radio value={1}>随访</Radio>
                      </Radio.Group>
                    </Form.Item>
                  </Col>
                </Row>

              </Form>
            </Row>
          </div>
        </Modal>
      </div>
    );
  }
}
